package org.wupuser.repository;

import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.Modifying;
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.query.Param;
import org.springframework.stereotype.Repository;
import org.springframework.transaction.annotation.Transactional;
import org.wupuser.model.Friend;
import org.wupuser.model.User;

import java.util.List;

@Repository
public interface FriendRepository extends JpaRepository<Friend, String> {
	@Query(nativeQuery = true, value = "select u.* from user u join friend f on u.id = f.user_id where f.user_id = :userId and f.status = 1 and u.is_deleted = 0")
	List<User> findUsersAllFriendById(
		@Param("userId") String userId
	);
	
	@Query(nativeQuery = true, value = "select * from friend where friend_id = :friendId and status = 0")
	List<Friend> findRequest(
		@Param("friendId") String friendId
	);
	
	@Transactional
	@Modifying
	@Query(nativeQuery = true, value = "insert  into friend(create_time,confirm_time,user_id,friend_id,status) values (:#{#friend.createTime},:#{#friend.confirmTime},:#{#friend.userId},:#{#friend.friendId},:#{#friend.status})")
	void sendRequestOrConfirmTowWay(Friend friend);
	
	@Transactional
	@Modifying
	@Query(nativeQuery = true, value = "update friend set status = 1,confirm_time = :#{#friend.confirmTime} where user_id = :#{#friend.userId} and friend_id = :#{#friend.friendId}")
	void confirmRequestFromFriend(
		Friend friend
	);
	
	@Transactional
	@Modifying
	@Query(nativeQuery = true, value = "delete from friend where user_id = :userId and friend_id = :friendId and status = 1")
	void deleteFriend(
		@Param("userId") String userId,
		@Param("friendId") String friendId
	);
}
